<template>
  <!-- v-loading="authorizeLoading" -->
  <div
    v-loading="authorizeLoading"
    class="Login"
    :element-loading-text="authorizeLoadingText"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#fff"
  >
    <!-- 头部 -->
    <div class="header">
      <div class="w1200">
        <router-link
          :to="{ name: 'Index' }"
          class="logo fl"
        ><img
          src="../../assets/images/logo.png"
        ></router-link>
      </div>
    </div>
    <div class="main">
      <div class="w1200">
        <!-- 登录 -->
        <div class="box fr">
          <div class="tabs">
            <div class="item" :class="form.loginMode == 1 ? 'active':''" @click="changeLoginMode(1)">
              短信登录
            </div>
            <div class="item" :class="form.loginMode == 2 ? 'active':''" @click="changeLoginMode(2)">密码登录</div>
          </div>
          <div v-if="form.loginMode == 1" @touchmove.prevent>
            <el-form ref="form" class="form" :model="form" :rules="rules">
              <el-form-item prop="mobile">
                <el-input
                  v-model.trim="form.mobile"
                  maxlength="11"
                  placeholder="请输入手机号"
                />
              </el-form-item>
              <el-form-item prop="dragVerify">
                <drag-verify
                  ref="dragVerify"
                  :width="330"
                  :height="42"
                  radius="0"
                  :is-passing.sync="isPassingFlag"
                  text="请按住滑块拖动"
                  success-text="验证通过"
                  handler-icon="el-icon-d-arrow-right"
                  success-icon="el-icon-circle-check"
                >
                  <i
                    v-show="!isPassingFlag"
                    slot="textBefore"
                    class="el-icon-lock"
                  />
                </drag-verify>
              </el-form-item>
              <el-form-item class="code" prop="captcha">
                <el-input
                  ref="code"
                  v-model="form.captcha"
                  maxlength="6"
                  placeholder="请输入验证码"
                />
                <el-button
                  type="text"
                  :disabled="disabledFlag"
                  @click="getCode"
                >{{ codeName }}</el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  class="btn"
                  @click="submit"
                >登录</el-button>
              </el-form-item>
              <!-- <el-form-item class="other" prop="agree">
                <div class="left fl">
                  <el-checkbox v-model="agreeFlag">我已同意</el-checkbox
                  ><router-link to="Index">用户协议和隐私政策</router-link>
                </div>
              </el-form-item> -->
            </el-form>
          </div>

          <div v-if="form.loginMode == 2" @touchmove.prevent>
            <el-form ref="form" class="form" :model="form" :rules="rules">
              <el-form-item prop="username">
                <el-input v-model.trim="form.username" placeholder="请输入手机号" maxlength="11" />
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model.trim="form.password" type="password" placeholder="请输入密码" />
              </el-form-item>
              <el-form-item prop="captcha">
                <el-input
                  ref="captcha"
                  v-model="form.captcha"
                  placeholder="请输入验证码"
                  name="captcha"
                  type="text"
                  maxlength="4"
                  tabindex="1"
                  autocomplete="on"
                >
                  <template slot="append"><img style="cursor: pointer;" :src="randomImg" alt="" @click="getRandomImage"> </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="btn" @click="submit">登录</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <div class="footer">
      <div class="w1200">
        <div class="copyRight fl">
          Copyright © 2020 黄河人才网 <a href="https://beian.miit.gov.cn/" target="_blank">豫ICP备19003500号-2</a>
          <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=41010502004793" target="_blank">
            <img src="../../assets/images/emblem.png" alt="" class="ml10 mr10">
            <span>豫公网安备 41010502004793号</span>
          </a>
        </div>
        <div class="friendLink fr">
          <div class="label">友情链接：</div>
          <div class="box">
            <div class="active">河南省投资集团</div>
            <dl>
              <dd>
                <a href="http://www.hnic.com.cn/" target="_blank">河南省投资集团</a>
              </dd>
            </dl>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import '@/utils/jsencrypt.min.js'
import dragVerify from 'vue-drag-verify2'
// phoneLogin
import { getSmsCode, authorize, getSmsCodeToken, getRandomImage } from '@/api/user'
import { getQueryObject } from '@/utils/index'
// import { setToken } from '@/utils/auth'
// import store from 'vuex'
export default {
  // 组件注入
  components: { dragVerify },
  // 接受父组件传递的值
  props: [],
  // 存放数据
  data() {
    // 滑块验证校验方法
    var passcall = (rule, value, callback) => {
      if (!this.isPassingFlag) {
        return callback(new Error('请拖动滑块进行验证'))
      } else {
        callback()
      }
    }
    // 同意协议校验方法
    var agree = (rule, value, callback) => {
      if (!this.agreeFlag) {
        return callback(new Error('请阅读并同意用户协议和隐私政策'))
      } else {
        callback()
      }
    }
    // 验证码错误
    var codeErr = (rule, value, callback) => {
      if (this.codeErr) {
        return callback(new Error('验证码错误'))
      } else {
        callback()
      }
    }
    return {
      randomImg: '',
      authorizeLoading: true, // 授权登录
      authorizeLoadingText: '', //
      type: 1, // 0 注册  1登录
      phone: '', // 手机号
      code: '', // 验证码

      agreeFlag: false, // 同意隐私
      codeName: '获取验证码',
      disabledFlag: false, // 获取验证码能否点击
      time: 60,
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      form: {
        mobile: '', // 手机号
        captcha: '', // 验证码
        userType: 2,
        username: '',
        password: '',
        checkKey: '', // 验证码key
        loginMode: 1 // 登录方式 2 密码登录 1 手机号登录
      },
      isPassingFlag: false, // 默认滑块验证状态
      codeErr: false, // 验证码错误
      rules: {
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: this.$telText, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          // { validator: this.$telText, trigger: 'blur' }
          {
            validator: (rule, value, callback) => {
              var mobile = /^1(3|4|5|6|7|8|9)\d{9}$/
              var rule_1 = /^41\d{4}$/
              if (mobile.test(value)) {
                callback()
              } else if (rule_1.test(value)) {
                callback()
              } else {
                return callback(new Error('请输入手机号/行政区编码'))
              }
            }
          }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' }
        ],
        dragVerify: [{ validator: passcall, trigger: 'blur' }],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: codeErr, trigger: 'blur' }
        ],
        agree: [{ validator: agree, trigger: 'blur' }]
      },
      redirect: undefined,
      otherQuery: {}
    }
  },
  // 监控data中的数据变化
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // const url = location.search // 获取url中"?"符后的字串
    // const url = 'https://testadmin.huanghehr.com/?code=efa4cbf2ff9298355298986278dfd419&userType=3&scope=any#/'
    // console.log(url.search)
    const theRequest = getQueryObject(location.href)
    // const theRequest = getQueryObject('https://testadmin.huanghehr.com/?code=b11691b98820e5ccf3290c4d246a0637&userType=3&scope=any#/login?redirect=%2F')
    // if (url.indexOf('?') != -1) {
    //   const str = url.substr(1)
    //   const strs = str.split('&')
    //   for (var i = 0; i < strs.length; i++) {
    //     theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
    //   }
    // }
    console.log(theRequest)
    if (theRequest.code) {
      authorize({
        code: theRequest.code
      }).then(res => {
        this.$store.dispatch('user/authorizelogin', res.message).then(async() => {
          // this.$router.push({ path: '/' })
          const { roles } = await this.$store.dispatch('user/getInfo')
          const accessRoutes = await this.$store.dispatch('permission/generateRoutes', roles)
          this.$router.addRoutes(accessRoutes)
          // this.$router.push({ path: accessRoutes[0].path })
          location.href = location.origin + '/#' + this.generatePath(accessRoutes[0], '')
        })
      }).catch(() => {
        // this.authorizeLoadingText = '登录失败，请向管理员确认是否拥有对应权限'
        // this.$message.error(this.authorizeLoadingText)
        this.$confirm('您没有任何权限，可请管理员设置后重新登录', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('user/resetToken', {}, { root: true }).then(() => {
            // this.authorizeLoading = false
            location.href = location.origin + '/#/'
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // })
        })
        // setTimeout(function(){ alert("Hello"); }, 3000);
        // window.location = 'http://i.hnic.com.cn'
      })
    } else {
      this.authorizeLoading = false
    }
    //   this.authorizeLoading = true
    // this.authorizeLoadingText = '登录失败，请向管理员确认是否拥有对应权限'
    // this.$message.error( this.authorizeLoadingText);
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 方法集合
  methods: {
    /**
       * 获取验证码
       */
    getRandomImage() {
      const time = new Date().getTime()
      this.form.checkKey = time
      getRandomImage({ time: time }).then(res => {
        this.randomImg = res.result
      })
    },
    generatePath(item, str) {
      console.log(item.originPath)
      str += item.originPath
      if (item.children && item.children.length) {
        return this.generatePath(item.children[0], str)
      } else {
        console.log(str)
        return str
      }
    },
    // 登录方式
    changeLoginMode(mode) {
      this.form.loginMode = mode
      if (mode == 2) {
        this.getRandomImage()
      }
      this.$refs.form.resetFields()
    },
    // 切换登录注册
    changeType(type) {
      this.type = type
      this.phone = ''
      this.code = ''
      this.disabledFlag = false
      // 验证滑块重置
      this.isPassingFlag = false
      this.$refs.dragVerify.reset()
    },
    // 获取验证码
    getCode() {
      this.$refs.form.validateField(['mobile'], (valid) => {
        if (valid) return
        this.$refs.form.validateField('dragVerify', (valid) => {
          if (valid) return
          // 获取验证码token
          getSmsCodeToken({
            'mobile': this.form.mobile
          }).then(res => {
            if (res.code === 200) {
              const token = res.result.token
              const sign = this.$md5(token + this.form.mobile + 'EmxJk0VFBgtPfCU5XtZxiVk6rkIGBLwY')
              // 获取验证码接口
              const that = this
              that.disabledFlag = true
              const interval = window.setInterval(function() {
                that.codeName = '已发送' + that.time + 's'
                --that.time
                if (that.time < 0) {
                  that.codeName = '重新发送'
                  that.time = 60
                  that.disabledFlag = false
                  window.clearInterval(interval)
                }
              }, 1000)
              getSmsCode({
                'token': token,
                'mobile': this.form.mobile,
                'sign': sign
              }).then((res) => {
                console.log(res)
                if (res.code === 200) {
                  this.$message.success('验证码发送成功')
                } else {
                  this.$message.error(res.message)
                }
              })
            } else {
              this.$message.error(res.message)
            }
          })
        })
      })
    },
    // 注册/登录
    submit() {
      // console.log(1111)
      this.$refs.form.validate((valid) => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(this.form))
          if (form.password) {
            var encrypt = new JSEncrypt()
            encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRYwEHVtYKjqQ5VZEzVkPJqSWwokUy7GYZdjB+aUZDNioAWPXZ3A9HlOjp5FLbHEmLtIVt7qFX0U/E8xl9Ar1rePRUOijtxRBjpWTdW9f9DCw6CY7dPcXvxCKbshf1lSYEysu3Kphb+44/meqrGKuYnqJTYQVcjNXSmtMXFto08QIDAQAB')
            form.password = encrypt.encrypt(form.password)
          }
          this.$store.dispatch('user/login', form)
            .then(async() => {
              // this.$router.push({
              //   path: this.redirect || '/',
              //   query: this.otherQuery
              // })
              const { roles } = await this.$store.dispatch('user/getInfo')
              const accessRoutes = await this.$store.dispatch('permission/generateRoutes', roles)
              this.$router.addRoutes(accessRoutes)
              console.log(accessRoutes)
              this.$router.push({ path: this.generatePath(accessRoutes[0], '').replace(/\/\//g, '/') })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>
<style lang="scss">
  @mixin text-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  @mixin text-ellipsisclamp($clamp) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: $clamp;
    overflow: hidden;
  }
  @mixin transition {
    transition: all 0.3s;
  }
  .Login {
    .el-input-group__append{padding:0;}
    .header {
      height: auto;
      overflow: hidden;
      background: #fff;
      padding: 20px 0;
      position: relative;
      z-index: 0;
      .logo {
        width: 159px;
        margin-right: 110px;
        img {
          width: 100%;
        }
      }
    }
    .main {
      width: 100%;
      height: 684px;
      padding-top: 50px;
      overflow: hidden;
      background: url("../../assets/images/login-background.png") center no-repeat;
      background-size: cover;
      .box {
        user-select: none;
        width: 426px;
        height: 578px;
        background: #fff;
        padding: 16px;
        border-radius: 5px;
        .wechatLoginFlag {
          height: 38px;
          font-size: 13px;
          color: #999;
          cursor: pointer;
          span {
            width: 38px;
            height: 38px;
            background: url("../../assets/images/wechatLogin.png") center
            no-repeat;
            background-size: 100%;
            display: inline-block;
            vertical-align: -10px;
          }
        }
        .tabs {
          height: auto;
          overflow: hidden;
          text-align: center;
          margin-top: 50px;
          .item {
            font-size: 20px;
            color: #999;
            display: inline-block;
            margin: 0 50px;
            cursor: pointer;
            &.active {
              color: #000;
              font-weight: bold;
            }
          }
        }
        .form {
          width: 330px;
          height: auto;
          overflow: hidden;
          margin: 40px auto;
          .el-form-item {
            position: relative;
            .el-input {
              position: relative;
              z-index: 0;
            }
            .el-input__inner {
              height: 42px;
              line-height: 42px;
            }
            .drag_verify {
              line-height: 40px !important;
              border: 1px solid #dcdfe6;
            }
            &.code {
              .el-button {
                height: 39px;
                padding: 0 15px;
                position: absolute;
                z-index: 1;
                right: 1px;
                top: 2px;
                background: #fff;
                span {
                  position: relative;
                  top: -1px;
                }
              }
            }
            &.other {
              border: 0;
              font-size: 13px;
              color: #9e9e9e;
              margin-top: 50px;
              a {
                color: #9e9e9e;
                &:hover {
                  color: #348ce8;
                }
              }
              .el-checkbox {
                margin-right: 5px;
              }
              .right {
                cursor: pointer;
                span {
                  color: #348ce8;
                }
              }
              .wechat {
                @include transition();
                cursor: pointer;
                i {
                  font-size: 18px;
                  vertical-align: -2px;
                  margin-right: 5px;
                }
                &:hover {
                  color: #00ba0e;
                }
              }
            }
          }
          .btn {
            width: 100%;
            height: 50px;
            font-size: 16px;
          }
        }
      }
    }
    .footer {
      width: 100%;
      height: 100px;
      padding: 30px 0;
      .copyRight {
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        color: #999;
        a {
          color: #999;
        }
      }
      .friendLink {
        height: 40px;
        line-height: 40px;
        text-align: center;
        .label {
          font-size: 14px;
          color: #999;
          display: inline-block;
        }
        .box {
          width: 221px;
          height: 40px;
          border: 1px solid #dcdfe6;
          font-size: 14px;
          color: #999;
          display: inline-block;
          text-align: left;
          position: relative;
          .active {
            padding: 0 15px;
            cursor: pointer;
            @include transition();
            position: relative;
            &:hover {
              color: #333;
            }
            &:after {
              content: "";
              width: 100%;
              height: 1px;
              background: rgba($color: #eee, $alpha: 0.08);
              position: absolute;
              left: 0;
              top: 0;
            }
          }
          dl {
            margin: 0;
            padding: 0;
            display: none;
            height: 0;
            max-height: 260px;
            overflow: hidden;
            width: 220px;
            position: absolute;
            right: 0;
            bottom: 39px;
            border: 1px solid #dcdfe6;
            border-bottom: 0;
            background: #fff;
            dd {
              padding: 8px 15px;
              line-height: normal;
              cursor: pointer;
              @include transition();
              &:hover {
                color: #333;
              }
            }
          }
          &:hover {
            dl {
              height: auto;
              overflow: auto;
              padding: 8px 0;
              display: block;
            }
          }
          ::-webkit-scrollbar {
            width: 5px;
          }
        }
      }
    }
    .wechatLoginPop {
      width: 100%;
      height: 100%;
      position: fixed;
      left: 0;
      top: 0;
      z-index: 99;
      background: rgba($color: #000, $alpha: 0.8);
      .btnClose {
        position: absolute;
        right: 30px;
        top: 30px;
        color: #999;
        font-size: 30px;
        cursor: pointer;
        @include transition();
        &:hover {
          color: #fff;
        }
      }
      .wrap {
        width: 300px;
        height: 425px;
        position: relative;
        margin: auto;
        margin-top: 12%;
        iframe {
          width: 100%;
          height: 425px;
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          margin: auto;
        }
        .overdue {
          display: block;
          width: 282px;
          height: 282px;
          position: absolute;
          top: 45px;
          left: 9px;
          background-color: rgba(255, 255, 255, 0.9);
          text-align: center;
          .txt {
            margin-top: 90px;
            font-size: 20px;
            color: #414a60;
            letter-spacing: 1px;
            margin-bottom: 20px;
          }
          .btn {
            width: 150px;
            font-size: 16px;
          }
        }
      }
    }
  }
</style>
